
Ext.define('IAG.controller.UsersController', {
    extend: 'Ext.app.Controller',

    stores: ['UsersStore','SettingsInstanceStore'],

    models: ['User','LoginStatus'],

    views: ['user.Edit', 'user.List', 'user.Login'],

    refs: [
        {
            ref: 'usersPanel',
            selector: 'panel'
        }
    ],

    init: function() {
//    	debugger;
    	console.log("Starting iag...");
    	Ext.Ajax.defaultHeaders = {
   			 'Accept': 'application/json'
   			};
    	var lsModel		= Ext.ModelManager.getModel('IAG.model.LoginStatus');
    	lsModel.load(1,{
    		scope: this,
    		callback: function(record, operation) {
                if (record != null && record.get('loggedIn') ) {
                	this.showUsersAndSettings();
                }
                else {
                	Ext.create('IAG.view.user.Login').show();
                }
            }

    	});
        this.control({
            'userlist #usersGridPanel': {
                itemdblclick: this.editUser
            },
            'userlist button[action=showAddUser]': {
                click: this.showAddUser
            },
            'userlist button[action=reload]': {
                click: this.reload
            },
            'useredit button[action=save]': {
                click: this.updateUser
            },
            'login button[action=login]': {
                click: this.login
            },
            'userlist button[action=logout]': {
                click: this.logout
            },
            'userlist button[action=mainToolbarToggle]': {
                toggle: this.toggleUsersSettings
            },
            'userlist button[action=reloadAllFeeds]': {
                toggle: this.importFeeds,
                afterrender: this.afterRenderImportAllFeeds
            },
            'userlist button[action=cacheStatistics]': {
            	toggle: this.cacheStatistics
            }
            
        });
    },
    logout: function (button) {
    	var lr		= {
    			LoginRequest: {
	    			username	: "",
	    			md5Password : "",
	    			action : "logout"
    			}
    	}
    	var jsonString	= Ext.JSON.encode(lr);
    	Ext.Ajax.request({
    		method: "POST",
    		url: iag_constants.login_url,
    		params: jsonString,
    		scope: this,
    		headers : {
    			'Content-Type' : 'application/json'
    		},
    		success: function(response, opts) {
    			window.location.reload();
    		},
    		failure: function(response, opts) {
    			//window.location.reload();
    		}


    	});
    },
    login: function (button) {
    	var win    			= button.up('window'),
        form   				= win.down('form');
    	var jsonString	= Ext.JSON.encode({LoginRequest:form.getValues()});
    	Ext.Ajax.request({
    		method: "POST",
    		url: iag_constants.login_url,
    		params: jsonString,
    		scope: this,
    		headers : {
    			'Content-Type' : 'application/json'
    		},
    		success: function(response, opts) {
    			var obj = Ext.decode(response.responseText);
    			obj		= obj.LoginStatus;
    			console.dir(obj);
    			if ( obj.loggedIn ){
    				win.close();
    				Ext.Msg.alert("Login Response", obj.message, this.showUsersAndSettings, this);
    			}
    			else
    				Ext.Msg.alert("Login Response", obj.message);
    		},
    		failure: function(response, opts) {
    			Ext.Msg.alert("Login Response", "Problems on the server side. Try again.");
    			console.log('server-side failure with status code ' + response.status);
    		}


    	});
    },
    cacheStatistics: function (button) {
    	button.setIconCls("loadingIcon");
    	Ext.Ajax.request({
    		method: "POST",
    		url: iag_constants.cacheStatistics_url,
    		scope: this,
    		headers : {
    			'Content-Type' : 'application/json'
    		},
    		success: function(response, opts) {
    			var obj = Ext.decode(response.responseText);
    			obj		= obj.Response;
    			if ( obj.status="ok" ){
    				Ext.Msg.alert("Server Response", obj.message);
    			}
    			else
    				Ext.Msg.alert("Server Response", "There was an error creating the statistics. Please contact the system administrator");
    			
    			button.toggle(false, true);
    			button.setIconCls("cacheStatisticsButton");
    		},
    		failure: function(response, opts) {
    			Ext.Msg.alert("Server Response", "Updating the stats will take more time. Please check the stats link in about 10 mins.");
    			console.log('server-side failure with status code ' + response.status);
    			button.toggle(false, true);
    			button.setIconCls("cacheStatisticsButton");
    		}


    	});
    },
    importFeeds: function (button) {
    	var lController	= this.application.getController('IAG.controller.LogsController');
    	return lController.checkFeeds(button, iag_constants.importfeeds_reload_all_url);
    },
    afterRenderImportAllFeeds: function (button) {
    	this.application.getController('IAG.controller.LogsController').checkFeeds(button);
    },
    showAddUser: function (button) {
    	if ( this.newView == null)
    		this.newView = Ext.create('IAG.view.user.Edit');
    	
    	this.newView.show();
    },
    
    reload: function(button) {
    	this.getStore("UsersStore").load();
    },
    
    editUser: function(grid, record) {
    	console.log("Editing user");
        this.editView = Ext.create('IAG.view.user.Edit').show();

        this.editView.down('form').loadRecord(record);
    },

    updateUser: function(button) {
        var win    = button.up('window'),
            form   = win.down('form');
        
        if (win == this.newView) {
        	var record	= Ext.ModelManager.create(form.getValues(), 'IAG.model.User');
        	record.phantom	= true;
        	this.getStore("UsersStore").add( record );
        }
        else {
	        var record = form.getRecord();
	        var values = form.getValues();
	        record.set(values);
        }
        win.close();
    },
    showUsersAndSettings: function () {
    	var win 	= Ext.create('IAG.view.user.List');
    	win.show();
    	this.usersGrid	= win.getComponent(0);
    	this.getStore("UsersStore").load();
    },
    toggleUsersSettings: function(button) {
    	if ( button.pressed && button.id == 'settingsMainToolbarButton' ) {
    		var sController	= this.application.getController('IAG.controller.SettingsInstanceController');
    		var win	= button.up("window");
    		win.removeAll(false);
    		win.add(sController.getSettingsGrid() );
    		//win.items		= sController.getSettingsGrid();
    	}
    	if ( button.pressed && button.id == 'usersMainToolbarButton' ) {
    		var win	= button.up("window");
    		win.removeAll(false);
    		win.add( this.usersGrid );
    	}
    	if ( button.pressed && button.id == 'logsMainToolbarButton' ) {
    		var lController	= this.application.getController('IAG.controller.LogsController');
    		var win	= button.up("window");
    		win.removeAll(false);
    		win.add(lController.getLogsGrid() );
    	}
    }
    
});

